package com.agriculture.controller;

import agriculture.common.core.utils.StringUtils;
import agriculture.common.security.service.TokenService;
import agriculture.system.api.model.User;
import com.agriculture.service.UserService;



import com.agriculture.util.Result;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController

public class UserController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping(value = "/register", produces = "application/json;charset=UTF-8")
    public Result<?> register(@RequestBody User user) {
        System.out.println("------------------");
        try {
            // 调用 service 层注册方法
            userService.register(user);
            return new Result<>(200, "注册成功", null);
        } catch (Exception e) {
            return new Result<>(500, e.getMessage(), null);
        }
    }

    /**
     * 用户登录
     */
    // 登录接口，返回统一格式的 JSON 数据
    @PostMapping(value = "/login", produces = "application/json;charset=UTF-8")
    public Result<?> login(@RequestBody Map<String, String> loginData) {

        String phone    = loginData.get("phone");
        String password = loginData.get("password");

        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(password)) {
            return new Result<>(400, "手机号或密码不能为空", null);
        }

        try {
            // 1. 账号密码校验，拿到前端用户对象
            User user = userService.login(phone, password);

            // 2. 生成 JWT + 缓存登录态（内部已包装成 LoginUser 并写入 Redis）
            Map<String, Object> tokenMap = tokenService.createUserToken(user);
            // tokenMap 结构：
            // {
            //   "access_token": "...",
            //   "expires_in" : 720,
            //   "user"       : { ... }
            // }

            // 3. 直接返回
            return new Result<>(200, "登录成功", tokenMap);

        } catch (Exception e) {
            return new Result<>(500, e.getMessage(), null);
        }
    }



    /**
     * 用户查询
     */
    @GetMapping(value = "/getUserById/{userId}", produces = "application/json;charset=UTF-8")
    public Result<?> getUserById(@PathVariable("userId") Long userId) {
        User user = userService.findUserById(userId);
        if (user != null) {
            return new Result<>(200, "请求成功", user);
        } else {
            return new Result<>(500, "请求错误", null);
        }

    }



    @PostMapping(value = "/update", produces = "application/json;charset=UTF-8")
    public Result<?> updateUser(@RequestBody User user) {
        try {
            // 根据 user.id 更新数据
            userService.updateUser(user);
            return new Result<>(200, "更新成功", user);
        } catch (Exception e) {
            return new Result<>(500, e.getMessage(), null);
        }
    }
}